# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
"""
callplus系统页面元素操作
"""
import functools
import os
import sys

current_script_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_script_dir)
if parent_dir not in sys.path:
    sys.path.append(parent_dir)
from playwright.sync_api import Page
from pages.dialog_design_page import (
    DialogDesignMainPage,
    IndependentScenePage,
    ExperimentGroupPage,
    SceneCard,
    ProcessDesignPage,
    AddJumpBranch,
    AddNodeWindow,
    RecordSpeechWindow,
    NormalSpeechBox,
    StartNode,
    APINode,
    ClarifyNode,
    HangupNode,
    ConfigManagePage,
    VariableManagePage,
    AddVariableWindow,
    AudioManagePage,
    AddtoneWindow,
    TonePackInside,
    ChooseVariableWindow,
    HangupNodeSpeechBox,
    SceneAnalyzeRule,
    ResourceManagePage,
    IntentManagePage,
    SlotManagePage,
    GlobalEventPage,
)
from pages.home_page import HomePage
from pages.login_page import LoginPage
from pages.callin_task_page import CallInTaskPage
from pages.callout_task_page import CalloutTaskPage
from utils.helpers import read_yaml, get_now_time, mkdir, reload_wait, screenshot_dir

picture_index = 1
public_config = read_yaml("public.yaml")
headless = public_config.get("headless")
should_screenshot = public_config.get("should_screenshot")
now_time = get_now_time()
if should_screenshot:
    picture_dir = mkdir(screenshot_dir, now_time)  # 创建当前时间点的截图保存目录


def screenshot(page_name="new_page"):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(self, *args, **kwargs):
            global picture_index
            result = func(self, *args, **kwargs)  # 执行函数
            page = getattr(
                self, page_name if page_name in ("page", "new_page") else "new_page"
            )
            page.wait_for_load_state(
                "networkidle"
            )  # 等待网络几乎无活动，用于等待操作执行完成
            # 检查是否需要截图
            if should_screenshot:
                operate_desc = func.__doc__
                picture_name = f"{picture_index}-{operate_desc}.png"
                picture_path = os.path.join(picture_dir, picture_name)
                page.screenshot(path=picture_path)
                picture_index += 1
            return result

        return wrapper

    return decorator


class Login:
    def __init__(self, page):
        self.page = page
        self.login_page = LoginPage(self.page)

    @screenshot("page")
    def goto_url(self, url):
        """打开登录页面"""
        self.page.goto(url)

    @screenshot("page")
    def login(self, username, password):
        """输入用户名、密码进行登录"""
        self.login_page.aiforce_id().fill(username)
        self.login_page.password().fill(password)
        self.login_page.button("登录").click()
        self.page.wait_for_url("**/page/home", timeout=10000)

    @screenshot("page")
    def choose_business(self, business_name):
        """登录成功后选择业务"""
        self.login_page.button(business_name).click()


class HomePageOperate:
    def __init__(self, new_page: Page):
        self.new_page = new_page
        self.home_page = HomePage(self.new_page)

    # @screenshot()
    # def choose_env(self, env_index):
    #     """切换环境"""
    #     self.home_page.env_dropbox().click()
    #     self.home_page.env_option(env_index).click()

    # def get_current_business_name(self):
    #     """获取当前业务名"""
    #     current_business_name = self.home_page.current_business().text_content()
    #     return current_business_name

    # def get_current_username(self):
    #     """获取当前用户名"""
    #     current_username = (
    #         self.home_page.current_username().text_content()
    #     )  # 定位当前登录的用户名，需要去空格和去换行
    #     current_username = current_username.replace("\n", "")
    #     current_username = current_username.replace(" ", "")
    #     return current_username

    @screenshot()
    def click_left_menu(self, memu_name):
        """点击左侧一级菜单"""
        # self.home_page = HomePage(self.new_page)
        self.home_page.menu(memu_name).click()


class DialogDesign:
    """对话设计"""

    def __init__(self, new_page: Page):
        self.new_page = new_page
        self._dialog_design_main_page = DialogDesignMainPage(self.new_page)
        self._independent_scene_page = IndependentScenePage(self.new_page)
        self._experiment_group_page = ExperimentGroupPage(self.new_page)
        self._scene_card = SceneCard(self.new_page)
        self._process_design_page = ProcessDesignPage(self.new_page)
        self._add_jump_branch = AddJumpBranch(self.new_page)
        self._add_node_window = AddNodeWindow(self.new_page)
        self._record_speech_window = RecordSpeechWindow(self.new_page)
        self._robot_speech_box = NormalSpeechBox(self.new_page, "机器人话术")
        self._reply_speech_box = HangupNodeSpeechBox(self.new_page)
        self._start_node = StartNode(self.new_page)
        self._api_node = APINode(self.new_page)
        self._clarify_node = ClarifyNode(self.new_page)
        self._hangup_node = HangupNode(self.new_page)
        self._config_manage_page = ConfigManagePage(self.new_page)
        self._variable_manage_page = VariableManagePage(self.new_page)
        self._add_variable_window = AddVariableWindow(self.new_page)
        self._audio_manage_page = AudioManagePage(self.new_page)
        self._add_tone_window = AddtoneWindow(self.new_page)
        self._tone_pack_inside = TonePackInside(self.new_page)
        self._choose_variable_window = ChooseVariableWindow(self.new_page)
        self._scene_analyze_rule = SceneAnalyzeRule(self.new_page)
        self._resource_manage_page = ResourceManagePage(self.new_page)
        self._intent_manage_page = IntentManagePage(self.new_page)
        self._slot_manage_page = SlotManagePage(self.new_page)
        self._global_event_page = GlobalEventPage(self.new_page)

    @screenshot()
    def scene_tab_switch(self, tab_name):
        """独立场景&实验组tab页切换"""
        self._dialog_design_main_page.tab(tab_name).click()

    @screenshot()
    def create_independent_scene(self, scene_name, create_method="创建新场景"):
        """新建独立场景"""
        self._independent_scene_page.create_scene_button().click()
        self._independent_scene_page.scene_name_input().fill(scene_name)
        self._independent_scene_page.create_method_radio(create_method)
        self._independent_scene_page.button().click()

    @screenshot()
    def create_experiment_group(self, experiment_group_name):
        """新建实验组"""
        self._experiment_group_page.create_experiment_group_button().click()
        self._experiment_group_page.experiment_group_name_input().fill(
            experiment_group_name
        )
        self._experiment_group_page.button("确认").click()

    def find_experiment_group(self, experiment_group_name):
        """根据实验组名称查找实验组"""
        result = self._experiment_group_page.experiment_group_name(
            experiment_group_name
        )
        if result:
            return True
        else:
            return False

    @screenshot()
    def create_child_scene(
        self, experiment_group_name, child_scene_name, create_method="创建新场景"
    ):
        """新建实验组子场景"""
        self._experiment_group_page.create_experiment_group_child_scene_button(
            experiment_group_name
        ).click()
        self._experiment_group_page.scene_name_input().fill(child_scene_name)
        self._experiment_group_page.create_method_radio(create_method).click()
        self._experiment_group_page.button("确认").click()

    def find_child_scene(self, experiment_group_name, child_scene_name):
        """查找实验组下的子场景"""
        result = self._experiment_group_page.child_scene_name(
            experiment_group_name, child_scene_name
        )
        if result:
            return True
        else:
            return False

    @screenshot()
    def goto_generic_config_page(self, experiment_group_name):
        """进入实验组通用设置页面"""
        self._experiment_group_page.generic_config_button(experiment_group_name).click()

    @screenshot()
    def click_scene_card(self, scene_name):
        """点击场景卡片"""
        self._scene_card.scene_card(scene_name).click()

    @screenshot()
    def back_scene_list_page(self):
        """点击【返回】场景列表页面"""
        self._dialog_design_main_page.back_button().click()

    def scene_inside_tab_switch(self, tab_name):
        """场景详情页面顶部tab页切换"""
        self._dialog_design_main_page.scene_inside_tab(tab_name).click()

    def config_manage_tab_switch(self, tab_name):
        """配置管理左侧tab页切换"""
        self._config_manage_page.left_tab(tab_name).click()

    @screenshot()
    def add_variable(self, field_name, standard_name, default_value, field_type):
        """新增自定义变量"""
        self._variable_manage_page.button("新增字段").click()
        self._add_variable_window.field_input().fill(field_name)
        self._add_variable_window.standard_name_input().fill(standard_name)
        self._add_variable_window.default_value().fill(default_value)
        self._add_variable_window.field_type_dropbox().click()
        self._add_variable_window.field_type_option(field_type).click()
        self._add_variable_window.button("新增").click()

    @screenshot()
    def select_node(self, node_name):
        """选中节点"""
        # self._process_design_page.node(node_name).click(position={"x": 10, "y": 10})
        self._process_design_page.node(node_name).click(position={"x": 1, "y": 1})

    @screenshot()
    def start_node_add_dump_node(self, node_type="API节点"):
        """开始节点新增跳转节点"""
        self._start_node.tab("节点模板").click()
        self._start_node.node_type(node_type).click()
        self._start_node.button("确定").click()
        self.new_page.wait_for_timeout(500)

    @screenshot()
    def to_configure_api_node(self, api_node_name, url, request_parameters):
        """配置API节点"""
        if api_node_name:
            self._api_node.node_name_input().fill(api_node_name)
        self._api_node.url_input().fill(url)
        self._api_node.param_maneger_dropbox().click()
        self._api_node.req_param_maneger_textarea().clear()
        self._api_node.req_param_maneger_textarea().fill(request_parameters)

    @screenshot()
    def api_node_custom_jump_branch(
        self,
        branch_name,
        jump_condition_name,
        call_result=None,
        jump_node_name=None,
        jump_node_type=None,
        global_param=None,
        global_param_condition_option=None,
    ):
        """API节点新增自定义跳转分支"""
        self._api_node.button("新建分支").click()
        self._api_node.custom_button().click()
        self._add_jump_branch.branch_name_input().fill(branch_name)
        self._add_jump_branch.condition_name_dropbox().click()
        self._add_jump_branch.condition_name_option(jump_condition_name).click()
        if jump_condition_name == "接口调用":
            self._add_jump_branch.interface_call_result_dropbox().click()
            self._add_jump_branch.interface_call_result_option(call_result).click()
        elif jump_condition_name == "全局参数":
            self._add_jump_branch.global_param_input().fill(global_param)
            self._add_jump_branch.global_param_condition_dropbox().click()
            self._add_jump_branch.global_param_condition_option(
                global_param_condition_option
            ).click()
        self._add_jump_branch.button("新建节点").click()
        self._add_node_window.node_name_input().fill(jump_node_name)
        self._add_node_window.node_type_dropbox().click()
        self._add_node_window.node_type_option(jump_node_type).click()
        self._add_node_window.button("立即创建").click()
        self._add_jump_branch.button("完成").click()

    @screenshot()
    def save_api_node_config(self):
        """保存节点配置"""
        self._api_node.button("保存").click()

    def click_node_edit_button(self, node_name):
        """点击指定节点上的【编辑】按钮"""
        self._process_design_page.node_edit_button(node_name).click()

    @screenshot()
    def add_record_speech(self, record_speech_content):
        """新增录音话术"""
        self._record_speech_window.button("新增话术").click()
        self._record_speech_window.record_speech_input().fill(record_speech_content)
        self._record_speech_window.button("添加").click()

    @screenshot()
    def choose_record_speech(self, record_speech_content):
        """选择录音话术"""
        self._record_speech_window.speech_choose_button(record_speech_content).click()

    @screenshot()
    def robot_speech_box_click_button(self, button_name):
        """点击机器人话术框上的按钮"""
        self._robot_speech_box.tag(button_name).click()

    @screenshot()
    def robot_speech_box_fill_content(self, content):
        """机器人话术框输入文字"""
        self._robot_speech_box.input(content)

    @screenshot()
    def robot_speech_box_fill_variable(self, variable_name, broadcast_method="录音"):
        """机器人话术框输入变量"""
        self._choose_variable_window.variable_broadcast_method(
            variable_name, broadcast_method
        ).click()
        self._choose_variable_window.apple_to_speech_button(variable_name).click()

    @screenshot()
    def clarify_node_custom_jump_branch(
        self,
        branch_name,
        jump_condition_name,
        jump_node_name,
        jump_node_type,
        intent_condition=None,
        intent_name=None,
        solt_name=None,
        solt_condition=None,
        global_param=None,
        global_param_condition_option=None,
        node_stay_option=None,
    ):
        """澄清节点新增自定义跳转分支"""
        self._clarify_node.button("新建分支").click()
        self._clarify_node.custom_button().click()
        self._add_jump_branch.branch_name_input().fill(branch_name)
        self._add_jump_branch.condition_name_dropbox().click()
        self._add_jump_branch.condition_name_option(jump_condition_name).click()
        if jump_condition_name == "意图":
            self._add_jump_branch.intent_condition_dropbox().click()
            self._add_jump_branch.intent_condition_option(intent_condition).click()
            self._add_jump_branch.intent_dropbox()
            self._add_jump_branch.intent_option(intent_name)
        elif jump_condition_name == "词槽":
            self._add_jump_branch.solt_dropbox().click()
            self._add_jump_branch.solt_option(solt_name).click()
            self._add_jump_branch.solt_condition_dropbox().click()
            self._add_jump_branch.solt_condition_option(solt_condition).click()
        elif jump_condition_name == "全局参数":
            self._add_jump_branch.global_param_input().fill(global_param)
            self._add_jump_branch.global_param_condition_dropbox().click()
            self._add_jump_branch.global_param_condition_option(
                global_param_condition_option
            ).click()
        elif jump_condition_name == "节点停留":
            self._add_jump_branch.node_stay_dropbox().click()
            self._add_jump_branch.node_stay_option(node_stay_option)
        self._add_jump_branch.button("新建节点").click()
        self._add_node_window.node_name_input().fill(jump_node_name)
        self._add_node_window.node_type_dropbox().click()
        self._add_node_window.node_type_option(jump_node_type).click()
        self._add_node_window.button("立即创建").click()
        self._add_jump_branch.button("完成").click()

    @screenshot()
    def save_clarify_node_config(self):
        """保存澄清节点配置"""
        self._clarify_node.button("保存").click()

    def drag_node(self, node_name, drag_distance=200):
        node_xpath = f"//p[text()='{node_name}']/ancestor::*[name()='g']"
        self.new_page.click(
            node_xpath, position={"x": 10, "y": 10}
        )  # 在节点小方块上停留，这样节点才不会被遮挡可以操作
        node_element = self.new_page.locator(node_xpath)
        # 往右侧拖动“邀请加微”节点
        box = node_element.bounding_box()
        self.new_page.mouse.move(
            box["x"] + box["width"] / 2, box["y"] + box["height"] / 2
        )
        self.new_page.mouse.down()
        mov_x = box["x"] + box["width"] / 2 + drag_distance
        self.new_page.mouse.move(mov_x, box["y"] + box["height"] / 2)
        self.new_page.mouse.up()
        self.new_page.wait_for_timeout(1000)

    @screenshot()
    def reply_speech_box_click_button(self, button_name):
        """点击回复话术框上的按钮"""
        self._reply_speech_box.tag(button_name).click()

    @screenshot()
    def reply_speech_box_fill_content(self, content):
        """回复话术框输入文字"""
        self._reply_speech_box.input(content)

    @screenshot()
    def reply_speech_box_fill_variable(self, variable_name, broadcast_method="录音"):
        """回复话术框输入变量"""
        self._choose_variable_window.variable_broadcast_method(
            variable_name, broadcast_method
        ).click()
        self._choose_variable_window.apple_to_speech_button(variable_name).click()

    @screenshot()
    def save_hangup_node_config(self):
        """保存挂机节点配置"""
        self._hangup_node.button("保存").click()

    @screenshot()
    def publish_scene(self):
        """发布场景"""
        self._dialog_design_main_page.publish_scene_button().click()
        self._dialog_design_main_page.toast_message("发布成功").wait_for(
            state="visible"
        )

    @screenshot()
    def publish_experiment_group(self):
        """发布实验组"""
        self._dialog_design_main_page.publich_experiment_group().click()

    @screenshot()
    def add_tone_pack(self, tone_page_name, remark=None):
        """添加音色包"""
        self._audio_manage_page.add_tone_button().click()
        self._add_tone_window.tone_page_name_input().fill(tone_page_name)
        if remark:
            self._add_tone_window.remark_textarea().fill(remark)
        self._add_tone_window.button("确认").click()

    @screenshot()
    def upload_recording_files(self, tone_page_name, normal_recording_files):
        """给指定音色包上传录音文件"""
        self._audio_manage_page.tone_pack_name(tone_page_name).click()
        self._tone_pack_inside.import_record_file_button().click()
        self.wait(500)  # 不进行等待的话,上传录音会提示"未匹配话术"
        upload_file_area = self._tone_pack_inside.normal_recording_upload_area()
        upload_file_area.set_input_files(normal_recording_files)
        self.wait(1000)
        self._tone_pack_inside.check_all_box().click()
        self.wait(1000)
        self._tone_pack_inside.normal_recording_import_button().click()
        # 等待常量录音列表所有录音状态变更为"已上线"
        reload_wait(
            self.new_page,
            "//tr[@class='el-table__row']",
            "xpath=.//span[text()='已上线']",
        )

    @screenshot()
    def upload_variable_recording_files(
        self, variable_standard_name, variable_recording_files
    ):
        """上传变量录音文件"""
        self._tone_pack_inside.tab("变量录音库").click()
        self._tone_pack_inside.import_record_file_button().click()
        self._tone_pack_inside.belong_variable_dropbox().click()
        self._tone_pack_inside.belong_variable_option(variable_standard_name).click()
        self._tone_pack_inside.variable_recording_upload_area().set_input_files(
            variable_recording_files
        )
        self._tone_pack_inside.variable_recording_import_button().click()
        self._tone_pack_inside.variable_recording_online_button().click()

    @screenshot()
    def add_dialog_user_prefer(self, ouput_item_infos: list):
        """添加场景分析规则（客户意向）"""
        """
        :param ouput_item_infos: 输出项详细信息。示例如下：
        [
    {
        "output_item_value": "高意向",
        "condition": [
            "流程触发",
            "节点",
            "发起加微",
            "触发"
        ]
    },
    {
        "output_item_value": "无意向",
        "condition": [
            "词槽值",
            "通用否定",
            "等于",
            "通用否定"
        ]
    }
]
        """
        output_item_index = 1
        for ouput_item_info in ouput_item_infos:
            self._scene_analyze_rule.add_ouput_button().click()  # 点击【添加输出项】
            custom_intent_section = self._scene_analyze_rule.output_item_section(
                "客户意向", output_item_index
            )
            output_item_value = ouput_item_info.get(
                "output_item_value"
            )  # 获取输出的固定值
            # 固定值输入框填写
            self._scene_analyze_rule.fixed_value_input(
                custom_intent_section, output_item_index
            ).fill(output_item_value)
            self._scene_analyze_rule.add_condition_button().click()  # 点击【添加条件】
            condition = ouput_item_info.get("condition")
            condition_len = len(condition)
            for x in range(
                condition_len
            ):  # 子条件下拉框从左到右，以此点击展开下拉框，而后选择可选项
                self._scene_analyze_rule.condition_dropbox(
                    custom_intent_section, dropbox_index=x
                ).click()
                self.new_page.wait_for_timeout(500)
                self._scene_analyze_rule.condition_option(condition[x]).click()
            # 保存输出项配置
            self._scene_analyze_rule.output_item_button(
                custom_intent_section, "确认"
            ).click()
            output_item_index += 1
        self._scene_analyze_rule.buttom_button().click()

    @screenshot()
    def add_call_num(self, call_num, purpose):
        """添加呼叫号码"""
        self._resource_manage_page.add_num_button().click()  # 点击【添加号码】按钮
        self._resource_manage_page.num_dropbox().click()  # 点击展开“号码”下拉框
        self._resource_manage_page.dropbox_option(
            call_num
        ).click()  # “号码”下拉框选择目标号码
        self._resource_manage_page.num_purpose(purpose).click()  # 选择号码“用途”
        self._resource_manage_page.add_num_window_button().click()  # 点击添加号码窗口【保存】按钮

    @screenshot()
    def configure_resource(
        self, asr_name, play_mode, tts_name, tone_name="小娜", speed=1.0, volume=1.5
    ):
        """配置ASR和TTS资源"""
        self._resource_manage_page.asr_dropbox().click()  # 点击展开“ASR资源”下拉框
        self._resource_manage_page.dropbox_option(
            asr_name
        ).click()  # 点击展开“ASR资源”下拉框可选项
        self._resource_manage_page.play_mode(play_mode).click()  # 选择播音模式
        self._resource_manage_page.tts_dropbox().click()  # 展开“TTS资源”下拉框
        self._resource_manage_page.dropbox_option(
            tts_name
        ).click()  # 选择“TTS资源”下拉框可选项
        self.wait(300)
        self._resource_manage_page.tone_dropbox().click()  # 展开“音色”下拉框
        self._resource_manage_page.dropbox_option(tone_name).click()  # 选择音色
        self._resource_manage_page.speed_input().clear()
        self._resource_manage_page.speed_input().fill(str(speed))
        self._resource_manage_page.volume_input().clear()
        self._resource_manage_page.volume_input().fill(str(volume))
        self._resource_manage_page.button().click()

    @screenshot()
    def publish_all_intent(self):
        """发布全部意图"""
        self._intent_manage_page.batch_publish().click()  # 点击【批量发布】按钮
        self._intent_manage_page.publish_intent().click()  # 点击【发布全部意图】
        self._intent_manage_page.toast_message("发布成功").wait_for(state="visible")

    @screenshot()
    def publish_all_slot(self):
        """发布全部词槽"""
        self._slot_manage_page.batch_publish_button().click()  # 点击【批量发布】按钮
        self._slot_manage_page.publish_slot().click()  # 点击【发布全部词槽】
        self._slot_manage_page.toast_message("发布成功").wait_for(state="visible")

    @screenshot()
    def create_global_event(self, global_event_name):
        """创建全局事件"""
        self._global_event_page.button(
            "创建全局事件"
        ).click()  # 点击【创建全局事件】按钮
        self._global_event_page.global_event_name_input().fill(
            global_event_name
        )  # 输入全局事件名称
        self._global_event_page.create_global_event_window_button().click()  # 点击【确认】按钮

    @screenshot()
    def configure_global_event(
        self,
        global_event_name,
        condition_limit,
        conditions: list[list],
        actions: list[list],
    ):
        """配置全局事件"""
        self._global_event_page.global_event_card(
            global_event_name
        ).click()  # 左侧全局事件列表选中全局事件
        init_node_name = f"全局条件-{global_event_name}"
        self._global_event_page.node(
            init_node_name
        ).click()  # 单击选中“全局事件-XXX”节点
        self._global_event_page.node_edit_button(
            init_node_name
        ).click()  # 点击“全局事件-XXX”节点上的【编辑】
        self._global_event_page.global_condition_configure_area_button(
            "添加条件限制"
        ).click()  # 点击【添加条件限制】
        self._global_event_page.condition_met_limit().click()  # 点击条件限制方法下拉框
        self._global_event_page.dropbox_option(
            condition_limit
        ).click()  # 选择满足一下任一/全部条件
        conditions_len = len(conditions)
        if conditions_len > 1:  # 有N个条件，则先添加N-1个条件
            for x in range(conditions_len - 1):
                self._global_event_page.global_condition_configure_area_button(
                    "添加新条件"
                ).click()  # 点击【添加新条件】
        for y in range(conditions_len):  # 遍历conditions二维列表，配置条件
            condition = conditions[y]
            condition_len = len(condition)
            for z in range(condition_len):
                condition_group_element = self._global_event_page.condition_group(
                    y
                )  # 定位第一组条件
                condition_input_element = self._global_event_page.condition_input(
                    condition_group_element, z
                )
                if condition_input_element.get_attribute(
                    "readonly"
                ):  # 元素带有readonly属性则为下拉框
                    condition_input_element.click()  # 点击展开下拉框
                    self._global_event_page.dropbox_option(
                        condition[z]
                    ).click()  # 选择下拉框可选项
                else:
                    condition_input_element.fill(
                        str(condition[z])
                    )  # 输入框则直接输入内容
        actions_len = len(actions)
        if actions_len > 1:  # 有N个动作，则先添加N-1个动作
            for x in range(actions_len - 1):
                self._global_event_page.global_condition_configure_area_button(
                    "添加动作"
                ).click()  # 点击【添加动作】
        for y in range(actions_len):
            action = actions[y]
            action_len = len(action)
            for z in range(action_len):
                action_group_element = self._global_event_page.action_group(y)
                action_input_element = self._global_event_page.condition_input(
                    action_group_element, z
                )
                if action_input_element.get_attribute(
                    "readonly"
                ):  # 元素带有readonly属性则为下拉框
                    action_input_element.click()  # 点击展开下拉框
                    self._global_event_page.dropbox_option(
                        action[z]
                    ).click()  # 选择下拉框可选项
                else:
                    action_input_element.fill(str(action[z]))  # 输入框则直接输入内容
        self._global_event_page.global_condition_configure_area_button("完成").click()
        self._global_event_page.global_condition_configure_area_button("保存").click()

    def wait(self, wait_time=3000):
        """页面等待3秒"""
        self.new_page.wait_for_timeout(wait_time)


class CalloutTask:
    def __init__(self, new_page: Page):
        self.new_page = new_page
        self._callout_task_page = CalloutTaskPage(self.new_page)

    @screenshot()
    def create_callout_task_and_import_phone(
        self,
        scene_name,
        scene_type="独立场景",
        experiment_group_name=None,
        customer_source="11111",
        case_id="11111",
        phone="18503056080",
    ):
        """新建外呼任务并导入单个手机号"""
        self._callout_task_page.button("新建任务").click()
        # 选择场景
        self._callout_task_page.choose_scene_placeholder().click()
        self._callout_task_page.scene_dropbox_option(scene_type).click()
        if scene_type == "实验组":
            self._callout_task_page.scene_dropbox_option(experiment_group_name).click()
        self._callout_task_page.scene_dropbox_option(scene_name).click()
        # 在高级设计中关闭限制营业时段
        self._callout_task_page.advance_setting_button().click()
        self._callout_task_page.limit_business_time_switch().click()
        # 点击【创建并导入号码】
        self._callout_task_page.create_task_window_button("创建并导入号码").click()
        self._callout_task_page.import_phone_tab("手动输入").click()
        self._callout_task_page.customer_source_input().fill(customer_source)
        self._callout_task_page.case_id_input().fill(case_id)
        self._callout_task_page.phone_input().fill(phone)
        self._callout_task_page.import_phone_window_button().click()
        self.new_page.wait_for_load_state("networkidle")

    @screenshot()
    def start_task(self, task_name):
        """开启外呼任务"""
        self._callout_task_page.start_task_button(task_name).click()


class CallinTask:
    def __init__(self, new_page: Page):
        self.new_page = new_page
        self.callin_task_page = CallInTaskPage(self.new_page)

    def create_callin_task(
        self, scene_type, experiment_group_name=None, scene_name=None
    ):
        self.callin_task_page.button("新建呼入任务").click()
        self.callin_task_page.choose_scene_placeholder().click()
        self.callin_task_page.scene_dropbox_option(scene_type).click()
        if scene_type == "实验组":
            self.callin_task_page.scene_dropbox_option(experiment_group_name).click()
        self.callin_task_page.scene_dropbox_option(scene_name).click()
        self.callin_task_page.button("保存并启用").click()


if __name__ == "__main__":
    import time
    from playwright.sync_api import sync_playwright
    from utils import helpers

    env_config = helpers.read_yaml("dev.yaml")
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(
            headless=False, channel="chrome", args=["--start-maximized"]
        )
        context = browser.new_context(no_viewport=True)
        page = context.new_page()
        login = Login(page)
        login.goto_url("http://172.18.160.155:40080/#/user/login")
        login.login("yaocheng1101@wezhuiyi.com", "admin@123")
        page.wait_for_url("**/page/home", timeout=10000)
        with context.expect_page() as new_page_info:
            login.choose_business("弘毅")
        new_page = new_page_info.value
        home_page_operate = HomePageOperate(new_page)
        home_page_operate.click_left_menu("呼出任务")
        callout_task = CalloutTask(new_page)
        callout_task.create_callout_task_and_import_phone(
            scene_type="实验组", experiment_group_name="CAPS", scene_name="CAPS-A"
        )
        """设计[开始]节点后的第一个API节点"""
        # dialog_design.select_node('开始')
        # dialog_design.start_node_add_dump_node('API节点')
        # custom_variable_api_node_info = env_config.get('custom_variable_api_node_info')
        # api_node_name = custom_variable_api_node_info.get('api_node_name')
        # url = custom_variable_api_node_info.get('url')
        # request_parameters = custom_variable_api_node_info.get('request_parameters')
        # dialog_design.to_configure_api_node(api_node_name, url, request_parameters)
        # custome_jump_branch = custom_variable_api_node_info.get('custome_jump_branch')
        # branch_name = custome_jump_branch.get('branch_name')
        # jump_condition_name = custome_jump_branch.get('jump_condition_name')
        # call_result = custome_jump_branch.get('call_result')
        # jump_node_name = custome_jump_branch.get('jump_node_name')
        # jump_node_type = custome_jump_branch.get('jump_node_type')
        # dialog_design.api_node_custom_jump_branch(branch_name, jump_condition_name, call_result, jump_node_name,
        #                                           jump_node_type)
        # dialog_design.save_api_node_config()
        """设计[核身]澄清节点"""
        # dialog_design.select_node('核身')
        # dialog_design.click_node_edit_button('核身')
        # dialog_design.robot_speech_box_click_button('禁止打断')
        # # 批量新增话术录音
        # dialog_design.robot_speech_box_click_button('录音')
        # record_speechs = env_config.get('record_speechs')
        # for record_speech in record_speechs:
        #     dialog_design.add_record_speech(record_speech)
        # # 选择话术录音
        # dialog_design.choose_record_speech('这边是樊登读书给你来电，我是樊登读书的书童。')
        # dialog_design.robot_speech_box_fill_content('请问是')
        # # 选择变量
        # dialog_design.robot_speech_box_click_button('变量')
        # dialog_design.robot_speech_box_fill_variable('称呼', '录音')
        # # 跳转分支
        # heshen_clarify_node_info = env_config.get('heshen_clarify_node_info')
        # for heshen_jump_info in heshen_clarify_node_info:
        #     branch_name = heshen_jump_info.get('branch_name')
        #     jump_condition_name = heshen_jump_info.get('jump_condition_name')
        #     solt_name = heshen_jump_info.get('solt_name')
        #     solt_condition = heshen_jump_info.get('solt_condition')
        #     jump_node_name = heshen_jump_info.get('jump_node_name')
        #     jump_node_type = heshen_jump_info.get('jump_node_type')
        #     dialog_design.clarify_node_custom_jump_branch(branch_name=branch_name,
        #                                                   jump_condition_name=jump_condition_name,
        #                                                   solt_name=solt_name, solt_condition=solt_condition,
        #                                                   jump_node_name=jump_node_name,
        #                                                   jump_node_type=jump_node_type)
        # dialog_design.save_clarify_node_config()
        """设计[邀请加微]澄清节点"""
        # node_name = '邀请加微'
        # dialog_design.drag_node(node_name)
        # dialog_design.click_node_edit_button(node_name)
        # dialog_design.robot_speech_box_click_button('禁止打断')
        # dialog_design.robot_speech_box_click_button('录音')
        # dialog_design.choose_record_speech('平日书童不会打扰到您的，我用企业微信添加您好吧？')
        # # 跳转分支
        # invite_clarify_node_info = env_config.get('invite_clarify_node_info')
        # for invite_jump_info in invite_clarify_node_info:
        #     branch_name = invite_jump_info.get('branch_name')
        #     jump_condition_name = invite_jump_info.get('jump_condition_name')
        #     solt_name = invite_jump_info.get('solt_name')
        #     solt_condition = invite_jump_info.get('solt_condition')
        #     jump_node_name = invite_jump_info.get('jump_node_name')
        #     jump_node_type = invite_jump_info.get('jump_node_type')
        #     dialog_design.clarify_node_custom_jump_branch(branch_name=branch_name,
        #                                                   jump_condition_name=jump_condition_name,
        #                                                   solt_name=solt_name,
        #                                                   solt_condition=solt_condition,
        #                                                   jump_node_name=jump_node_name,
        #                                                   jump_node_type=jump_node_type)
        # dialog_design.save_clarify_node_config()
        """设计[非本人]挂机节点"""
        # node_name = '非本人'
        # # dialog_design.drag_node(node_name, -200)
        # dialog_design.select_node(node_name)
        # dialog_design.click_node_edit_button(node_name)
        # dialog_design.reply_speech_box_click_button('禁止打断')
        # dialog_design.reply_speech_box_click_button('挂机')
        # dialog_design.reply_speech_box_click_button('录音')
        # dialog_design.choose_record_speech('很抱歉打扰您了，祝您生活愉快，再见。')
        # dialog_design.save_hangup_node_config()
        """设计[拒绝加微]挂机节点"""
        # node_name = '拒绝发短'
        # dialog_design.drag_node(node_name, -200)
        # dialog_design.select_node(node_name)
        # dialog_design.click_node_edit_button(node_name)
        # dialog_design.reply_speech_box_click_button('禁止打断')
        # dialog_design.reply_speech_box_click_button('挂机')
        # dialog_design.reply_speech_box_click_button('录音')
        # dialog_design.choose_record_speech('很抱歉打扰您了，祝您生活愉快，再见。')
        # dialog_design.save_hangup_node_config()
        """设计[发起加微]API节点"""
        # node_name = '发送短信'
        # dialog_design.select_node(node_name)
        # dialog_design.click_node_edit_button(node_name)
        # launch_add_v_node_info = env_config.get('launch_add_v_node_info')
        # url = launch_add_v_node_info.get('url')
        # req = launch_add_v_node_info.get('req')
        # dialog_design.to_configure_api_node('', url, req)
        # branch_name = launch_add_v_node_info.get('branch_name')
        # jump_condition_name = launch_add_v_node_info.get('jump_condition_name')
        # interface_condition = launch_add_v_node_info.get('interface_condition')
        # jump_node_name = branch_name
        # jump_node_type = launch_add_v_node_info.get('jump_node_type')
        # dialog_design.api_node_custom_jump_branch(branch_name, jump_condition_name, interface_condition, jump_node_name,
        #                                           jump_node_type)
        # dialog_design.save_api_node_config()
        """设计[加微成功]挂机节点"""
        # node_name = "发短成功"
        # dialog_design.select_node(node_name)
        # dialog_design.click_node_edit_button(node_name)
        # dialog_design.reply_speech_box_click_button("禁止打断")
        # dialog_design.reply_speech_box_click_button("挂机")
        # dialog_design.reply_speech_box_click_button("录音")
        # dialog_design.choose_record_speech(
        #     "好的，感谢您对樊登读书的信任和支持，有什么问题呢您在微信上联系我，祝您生活愉快，再见。"
        # )
        # dialog_design.save_hangup_node_config()
        context.close()
        browser.close()
